package clsTwo1;

public class Shell {
    public static void sort(Comparable[] a) {  // 将a[]按升序排列
        int N = a.length;
        int h = 1;
        while (h < N / 3) h = 3 * h + 1; // 1, 4, 13, 40, 121, 364, 1093, ...
        while (h >= 1) {  // 将数组变为h有序
            for (int i = h; i < N; i++) {  // 将a[i]插入到a[i-h], a[i-2*h], a[i-3*h]...之中
                for (int j = i; j >= h && less(a[j], a[j - h]); j -= h) {
                    exch(a, j, j - h);
                }

            }
            h = h / 3;
        }
    }

    // less()方法: 比较两个元素的大小
    private static boolean less(Comparable v, Comparable w) {
        return v.compareTo(w) < 0;
    }

    // exch()方法: 交换数组中的两个元素
    private static void exch(Comparable[] a, int i, int j) {
        Comparable temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    // isSorted()方法: 检查数组是否已排序
    private static boolean isSorted(Comparable[] a) {
        for (int i = 1; i < a.length; i++)
            if (less(a[i], a[i - 1])) return false;
        return true;
    }

    // main()方法: 测试Shell排序
    public static void main(String[] args) {
        String[] a = {"S", "H", "E", "L", "L", "S", "O", "R", "T"};
        Shell.sort(a);
        assert isSorted(a);
        for (String s : a)
            System.out.print(s + " ");
    }
}
